<template>
  <div class="exam-taking-container">
    <!-- 考试头部 -->
    <div class="exam-header">
      <div class="exam-info">
        <h1>{{ exam.title }}</h1>
        <div class="exam-meta">
          <span>总题数：{{ exam.questionCount }}题</span>
          <span>考试时长：{{ exam.duration }}分钟</span>
          <span>及格分数：{{ exam.passingScore }}分</span>
        </div>
      </div>
      
      <div class="exam-timer">
        <div class="timer-display" :class="{ 'warning': timeRemaining < 300 }">
          <el-icon><Clock /></el-icon>
          <span>{{ formatTime(timeRemaining) }}</span>
        </div>
        <el-progress 
          :percentage="timeProgress" 
          :stroke-width="4"
          :show-text="false"
          :color="timeRemaining < 300 ? '#F56C6C' : '#409EFF'"
        />
      </div>
    </div>

    <!-- 考试内容 -->
    <div class="exam-content">
      <!-- 题目导航 -->
      <div class="question-nav">
        <div class="nav-header">
          <h3>题目导航</h3>
          <div class="progress-info">
            已答：{{ answeredCount }}/{{ totalQuestions }}
          </div>
        </div>
        
        <div class="nav-grid">
          <div 
            v-for="(question, index) in questions" 
            :key="question.id"
            class="nav-item"
            :class="{
              'current': currentQuestionIndex === index,
              'answered': question.answered,
              'marked': question.marked
            }"
            @click="goToQuestion(index)"
          >
            {{ index + 1 }}
          </div>
        </div>
        
        <div class="nav-legend">
          <div class="legend-item">
            <div class="legend-color current"></div>
            <span>当前题</span>
          </div>
          <div class="legend-item">
            <div class="legend-color answered"></div>
            <span>已答题</span>
          </div>
          <div class="legend-item">
            <div class="legend-color marked"></div>
            <span>标记题</span>
          </div>
        </div>
      </div>

      <!-- 题目区域 -->
      <div class="question-area">
        <div v-if="currentQuestion" class="question-container">
          <!-- 题目头部 -->
          <div class="question-header">
            <div class="question-number">
              第 {{ currentQuestionIndex + 1 }} 题 / 共 {{ totalQuestions }} 题
            </div>
            <div class="question-type">
              <el-tag :type="getQuestionTypeColor(currentQuestion.type)">
                {{ getQuestionTypeText(currentQuestion.type) }}
              </el-tag>
            </div>
          </div>

          <!-- 题目内容 -->
          <div class="question-content">
            <div class="question-title">
              <span class="question-score">({{ currentQuestion.score }}分)</span>
              <div v-html="currentQuestion.content"></div>
            </div>

            <!-- 选择题选项 -->
            <div v-if="isChoiceQuestion(currentQuestion.type)" class="question-options">
              <div 
                v-for="option in currentQuestion.options" 
                :key="option.id"
                class="option-item"
                :class="{ 'selected': isOptionSelected(option.id) }"
                @click="selectOption(option.id)"
              >
                <div class="option-label">{{ option.label }}</div>
                <div class="option-content" v-html="option.content"></div>
              </div>
            </div>

            <!-- 填空题 -->
            <div v-else-if="currentQuestion.type === 'FILL_BLANK'" class="fill-blank-area">
              <div 
                v-for="(blank, index) in currentQuestion.blanks" 
                :key="index"
                class="blank-item"
              >
                <label>第{{ index + 1 }}空：</label>
                <el-input 
                  v-model="blank.answer"
                  placeholder="请输入答案"
                  @input="updateAnswer"
                />
              </div>
            </div>

            <!-- 简答题 -->
            <div v-else-if="currentQuestion.type === 'SHORT_ANSWER'" class="short-answer-area">
              <el-input
                v-model="currentQuestion.answer"
                type="textarea"
                :rows="6"
                placeholder="请输入您的答案..."
                @input="updateAnswer"
              />
              <div class="word-count">
                字数：{{ getWordCount(currentQuestion.answer) }}
              </div>
            </div>

            <!-- 编程题 -->
            <div v-else-if="currentQuestion.type === 'CODING'" class="coding-area">
              <div class="coding-header">
                <el-select v-model="selectedLanguage" placeholder="选择编程语言">
                  <el-option 
                    v-for="lang in supportedLanguages" 
                    :key="lang.value"
                    :label="lang.label" 
                    :value="lang.value"
                  />
                </el-select>
                <el-button @click="runCode" :loading="runningCode" type="primary">
                  运行代码
                </el-button>
              </div>
              
              <div class="code-editor">
                <textarea 
                  v-model="currentQuestion.code"
                  class="code-textarea"
                  placeholder="请在此处编写代码..."
                  @input="updateAnswer"
                ></textarea>
              </div>
              
              <div v-if="codeResult" class="code-result">
                <h4>运行结果：</h4>
                <pre>{{ codeResult }}</pre>
              </div>
            </div>
          </div>

          <!-- 题目操作 -->
          <div class="question-actions">
            <div class="left-actions">
              <el-button 
                @click="toggleMark"
                :type="currentQuestion.marked ? 'warning' : ''"
                :icon="currentQuestion.marked ? 'StarFilled' : 'Star'"
              >
                {{ currentQuestion.marked ? '取消标记' : '标记题目' }}
              </el-button>
            </div>
            
            <div class="right-actions">
              <el-button 
                @click="previousQuestion" 
                :disabled="currentQuestionIndex === 0"
                icon="ArrowLeft"
              >
                上一题
              </el-button>
              <el-button 
                @click="nextQuestion" 
                :disabled="currentQuestionIndex === totalQuestions - 1"
                type="primary"
              >
                下一题
                <el-icon><ArrowRight /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 考试底部操作 -->
    <div class="exam-footer">
      <div class="footer-info">
        <span>已答题：{{ answeredCount }}/{{ totalQuestions }}</span>
        <span>剩余时间：{{ formatTime(timeRemaining) }}</span>
      </div>
      
      <div class="footer-actions">
        <el-button @click="saveAndExit" icon="DocumentCopy">
          保存并退出
        </el-button>
        <el-button 
          @click="submitExam" 
          type="danger"
          :disabled="!canSubmit"
        >
          提交考试
        </el-button>
      </div>
    </div>

    <!-- 提交确认对话框 -->
    <el-dialog v-model="submitDialogVisible" title="提交考试" width="400px">
      <div class="submit-summary">
        <p>您确定要提交考试吗？</p>
        <div class="summary-stats">
          <div>总题数：{{ totalQuestions }}</div>
          <div>已答题：{{ answeredCount }}</div>
          <div>未答题：{{ totalQuestions - answeredCount }}</div>
          <div>标记题：{{ markedCount }}</div>
        </div>
        <p class="warning-text">提交后将无法修改答案！</p>
      </div>
      <template #footer>
        <el-button @click="submitDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmSubmit" :loading="submitting">
          确认提交
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  startExam, 
  getExamRecord, 
  submitAnswer, 
  submitExam,
  getExamQuestions
} from '@/api/exam'

const route = useRoute()
const router = useRouter()

const loading = ref(true)
const submitting = ref(false)
const runningCode = ref(false)
const submitDialogVisible = ref(false)

const exam = ref({})
const examRecord = ref({})
const questions = ref([])
const currentQuestionIndex = ref(0)
const timeRemaining = ref(0)
const timer = ref(null)

const selectedLanguage = ref('javascript')
const codeResult = ref('')

const supportedLanguages = [
  { label: 'JavaScript', value: 'javascript' },
  { label: 'Python', value: 'python' },
  { label: 'Java', value: 'java' },
  { label: 'C++', value: 'cpp' }
]

// 计算属性
const currentQuestion = computed(() => {
  return questions.value[currentQuestionIndex.value]
})

const totalQuestions = computed(() => questions.value.length)

const answeredCount = computed(() => {
  return questions.value.filter(q => q.answered).length
})

const markedCount = computed(() => {
  return questions.value.filter(q => q.marked).length
})

const timeProgress = computed(() => {
  if (!exam.value.duration) return 0
  const totalTime = exam.value.duration * 60
  return ((totalTime - timeRemaining.value) / totalTime) * 100
})

const canSubmit = computed(() => {
  return answeredCount.value > 0
})

// 开始考试
const startExamSession = async () => {
  loading.value = true
  try {
    const examId = route.params.id
    
    // 开始考试
    const startRes = await startExam(examId)
    if (startRes.code === 200) {
      examRecord.value = startRes.data
      
      // 获取考试题目
      const questionsRes = await getExamQuestions(examId)
      if (questionsRes.code === 200) {
        questions.value = questionsRes.data.map(q => ({
          ...q,
          answered: false,
          marked: false,
          answer: '',
          selectedOptions: []
        }))
      }
      
      // 设置考试时间
      timeRemaining.value = exam.value.duration * 60
      startTimer()
    }
  } catch (error) {
    console.error('开始考试失败:', error)
    ElMessage.error('开始考试失败')
    router.push('/exam')
  } finally {
    loading.value = false
  }
}

// 计时器
const startTimer = () => {
  timer.value = setInterval(() => {
    if (timeRemaining.value > 0) {
      timeRemaining.value--
    } else {
      // 时间到，自动提交
      autoSubmit()
    }
  }, 1000)
}

const stopTimer = () => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
}

// 题目导航
const goToQuestion = (index) => {
  currentQuestionIndex.value = index
}

const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
  }
}

const nextQuestion = () => {
  if (currentQuestionIndex.value < totalQuestions.value - 1) {
    currentQuestionIndex.value++
  }
}

// 答题操作
const selectOption = (optionId) => {
  const question = currentQuestion.value
  
  if (question.type === 'SINGLE_CHOICE') {
    question.selectedOptions = [optionId]
  } else if (question.type === 'MULTIPLE_CHOICE') {
    const index = question.selectedOptions.indexOf(optionId)
    if (index > -1) {
      question.selectedOptions.splice(index, 1)
    } else {
      question.selectedOptions.push(optionId)
    }
  }
  
  updateAnswer()
}

const isOptionSelected = (optionId) => {
  return currentQuestion.value.selectedOptions.includes(optionId)
}

const updateAnswer = () => {
  const question = currentQuestion.value
  question.answered = true
  
  // 保存答案到服务器
  saveAnswer(question)
}

const saveAnswer = async (question) => {
  try {
    let answer = ''
    
    if (isChoiceQuestion(question.type)) {
      answer = question.selectedOptions.join(',')
    } else if (question.type === 'FILL_BLANK') {
      answer = question.blanks.map(b => b.answer).join('|')
    } else {
      answer = question.answer || question.code || ''
    }
    
    await submitAnswer(examRecord.value.id, question.id, answer)
  } catch (error) {
    console.error('保存答案失败:', error)
  }
}

const toggleMark = () => {
  currentQuestion.value.marked = !currentQuestion.value.marked
}

// 工具函数
const isChoiceQuestion = (type) => {
  return ['SINGLE_CHOICE', 'MULTIPLE_CHOICE'].includes(type)
}

const getQuestionTypeText = (type) => {
  const typeMap = {
    'SINGLE_CHOICE': '单选题',
    'MULTIPLE_CHOICE': '多选题',
    'FILL_BLANK': '填空题',
    'SHORT_ANSWER': '简答题',
    'CODING': '编程题'
  }
  return typeMap[type] || type
}

const getQuestionTypeColor = (type) => {
  const colorMap = {
    'SINGLE_CHOICE': 'success',
    'MULTIPLE_CHOICE': 'warning',
    'FILL_BLANK': 'info',
    'SHORT_ANSWER': 'primary',
    'CODING': 'danger'
  }
  return colorMap[type] || 'info'
}

const getWordCount = (text) => {
  return text ? text.length : 0
}

const formatTime = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  
  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${minutes}:${secs.toString().padStart(2, '0')}`
}

// 代码运行
const runCode = async () => {
  runningCode.value = true
  try {
    // 这里应该调用代码运行API
    codeResult.value = '代码运行成功！\n输出：Hello World'
    ElMessage.success('代码运行成功')
  } catch (error) {
    console.error('代码运行失败:', error)
    ElMessage.error('代码运行失败')
  } finally {
    runningCode.value = false
  }
}

// 考试提交
const submitExam = () => {
  submitDialogVisible.value = true
}

const confirmSubmit = async () => {
  submitting.value = true
  try {
    await submitExam(examRecord.value.id)
    ElMessage.success('考试提交成功')
    router.push(`/exam/result/${examRecord.value.id}`)
  } catch (error) {
    console.error('提交考试失败:', error)
    ElMessage.error('提交考试失败')
  } finally {
    submitting.value = false
    submitDialogVisible.value = false
  }
}

const autoSubmit = async () => {
  ElMessage.warning('考试时间已到，系统自动提交')
  await confirmSubmit()
}

const saveAndExit = async () => {
  try {
    await ElMessageBox.confirm('确定要保存并退出考试吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 保存当前状态并退出
    router.push('/exam')
  } catch {
    // 用户取消
  }
}

// 页面离开确认
const beforeUnload = (event) => {
  event.preventDefault()
  event.returnValue = '考试正在进行中，确定要离开吗？'
}

onMounted(() => {
  startExamSession()
  window.addEventListener('beforeunload', beforeUnload)
})

onUnmounted(() => {
  stopTimer()
  window.removeEventListener('beforeunload', beforeUnload)
})
</script>

<style lang="scss" scoped>
.exam-taking-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color-page);
}

.exam-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid var(--el-border-color-lighter);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.exam-info {
  h1 {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 8px;
  }
  
  .exam-meta {
    display: flex;
    gap: 24px;
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }
}

.exam-timer {
  text-align: right;
  min-width: 200px;
  
  .timer-display {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 8px;
    
    &.warning {
      color: var(--el-color-danger);
    }
  }
}

.exam-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.question-nav {
  width: 280px;
  background: white;
  border-right: 1px solid var(--el-border-color-lighter);
  padding: 20px;
  overflow-y: auto;
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  
  h3 {
    font-size: 16px;
    font-weight: 600;
  }
  
  .progress-info {
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }
}

.nav-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 8px;
  margin-bottom: 20px;
}

.nav-item {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: var(--el-color-primary);
  }
  
  &.current {
    background: var(--el-color-primary);
    color: white;
    border-color: var(--el-color-primary);
  }
  
  &.answered {
    background: var(--el-color-success-light-9);
    border-color: var(--el-color-success);
    color: var(--el-color-success);
  }
  
  &.marked {
    background: var(--el-color-warning-light-9);
    border-color: var(--el-color-warning);
    color: var(--el-color-warning);
  }
}

.nav-legend {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 4px;
  
  &.current {
    background: var(--el-color-primary);
  }
  
  &.answered {
    background: var(--el-color-success);
  }
  
  &.marked {
    background: var(--el-color-warning);
  }
}

.question-area {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.question-container {
  max-width: 800px;
  margin: 0 auto;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  
  .question-number {
    font-size: 18px;
    font-weight: 600;
  }
}

.question-content {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.question-title {
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 20px;
  
  .question-score {
    color: var(--el-color-primary);
    font-weight: 600;
    margin-right: 8px;
  }
}

.question-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.option-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: var(--el-color-primary);
    background: var(--el-color-primary-light-9);
  }
  
  &.selected {
    border-color: var(--el-color-primary);
    background: var(--el-color-primary-light-9);
  }
  
  .option-label {
    font-weight: 600;
    color: var(--el-color-primary);
    min-width: 24px;
  }
  
  .option-content {
    flex: 1;
    line-height: 1.6;
  }
}

.fill-blank-area {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.blank-item {
  display: flex;
  align-items: center;
  gap: 12px;
  
  label {
    min-width: 80px;
    font-weight: 500;
  }
  
  .el-input {
    flex: 1;
  }
}

.short-answer-area {
  .word-count {
    text-align: right;
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin-top: 8px;
  }
}

.coding-area {
  .coding-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }
  
  .code-editor {
    margin-bottom: 16px;
    
    .code-textarea {
      width: 100%;
      height: 300px;
      padding: 16px;
      border: 1px solid var(--el-border-color);
      border-radius: 8px;
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      font-size: 14px;
      line-height: 1.5;
      resize: vertical;
      
      &:focus {
        outline: none;
        border-color: var(--el-color-primary);
      }
    }
  }
  
  .code-result {
    background: var(--el-fill-color-extra-light);
    padding: 16px;
    border-radius: 8px;
    
    h4 {
      margin-bottom: 8px;
    }
    
    pre {
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      font-size: 14px;
      line-height: 1.5;
      margin: 0;
    }
  }
}

.question-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right-actions {
  display: flex;
  gap: 12px;
}

.exam-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-top: 1px solid var(--el-border-color-lighter);
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
}

.footer-info {
  display: flex;
  gap: 24px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.footer-actions {
  display: flex;
  gap: 12px;
}

.submit-summary {
  text-align: center;
  
  .summary-stats {
    background: var(--el-fill-color-extra-light);
    padding: 16px;
    border-radius: 8px;
    margin: 16px 0;
    
    div {
      margin-bottom: 4px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
  
  .warning-text {
    color: var(--el-color-danger);
    font-weight: 500;
    margin-top: 16px;
  }
}
</style>
